<?php

class ThingModel extends SCModel {
	
	/**
	 * 
	 * thing 类型，用于程序和数据库间数据转换
	 * @var array
	 */
	public static $_thingType = array(
		'thing' => 0,
		'blog' => 1,
		'photo' => 2,
		'music' => 3,
		'video' => 4
	);
	
	
	public function __construct() {
		parent::__construct();
	}
	
	/**
	 * 
	 * 翻译thing类型在数据库中的表示值
	 */
	public static function translateType($type) {
		if(isset(self::$_thingType[$type])) {
			return self::$_thingType[$type];
		}
		return null;
	}
	
	/**
	 * 
	 * 获取指定thing
	 * @param unknown_type $id
	 */
	public function getThing($id) {
		$thing = $this->from('thing')->where('id = '.$id)->limit(1)->find();
		return $this->assemblingThings(array($thing));
	}
	
	/**
	 * 
	 * 获取thing数据
	 * @param integer $id
	 * @param integer $user_id
	 */
	public function getThings($id, $user_id = 0) {
		$condition = $user_id ? 'user_id = '.$user_id : '1 = 1';
		if($id == 0) {
			$things = $this->from('thing')->where($condition)->order('id DESC')->limit(10)->find();
		} else {
			$condition .= ' AND id < '.$id;
			$things = $this->from('thing')->where($condition)->order('id DESC')->limit(10)->find();
		}
		
		return $this->assemblingThings($things);
	}
	/**
	 * 
	 * 组装其他信息到数据流中
	 * @param array $things
	 */
	public function assemblingThings(array $things) {
		$userModel = new UserModel();
		foreach($things as $key=>$thing) {
			$things[$key]->post_date = CommonFunction::friendlyTime($thing->post_date);
			$things[$key]->user = $userModel->getBasicInfo($thing->user_id);
			$things[$key]->like_num = $this->reset()->field('COUNT(*)')->from('liker')
				->where('related_id = '.$thing->id.' AND type = '.self::$_thingType['thing'])->findScalar();
			$things[$key]->comment_num = $this->reset()->field('COUNT(*)')->from('comment')
				->where('related_id = '.$thing->id.' AND type = '.self::$_thingType['thing'])->findScalar();
			switch($thing->type) {
				case self::$_thingType['blog']:
					$things[$key]->type_key = 'blog';
					$things[$key]->related = $this->reset()->from('tblog')->where('id = '.$thing->related_id)->findOne();
				break;
				
				case self::$_thingType['photo']:
					$things[$key]->type_key = 'photo';
					$tphoto = $this->reset()->from('tphoto')->where('id = '.$thing->related_id)->findOne();
					$tphoto->photos = $this->reset()->from('photo')->where('tphoto_id = '.$tphoto->id)->find();
					$things[$key]->related = $tphoto;
				break;
				
				case self::$_thingType['music']:
					
				break;
				
				case self::$_thingType['video']:
				break;
				
				default:
					$things[$key]->type_key = 'thing';
				break;
			}
		}
		
		return $things;
	}
	
} 